﻿using System;
using System.Globalization;
using System.Web.Mvc;
using BookShop.BLL;
using BookShop.DTO;
using BookShop.Library.Common;
using BookShop.Library.Constant;
using PagedList;

namespace BookShop.Admin.Controllers
{
    public class CustomerController : Controller
    {
        public ActionResult Add()
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.CustomerWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(string email, string birthdate, string address, string phone, string fullName,
            string username, string password)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.CustomerWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            string message;
            var customer = new Customer
            {
                Email = email,
                Address = address,
                Phone = phone,
                FullName = fullName,
                Username = username,
                Password = password,
                Status = CustomerStatus.Active
            };
            DateTime newBirthdate;
            var isValidBirthdate = DateTime.TryParse(birthdate, CultureInfo.CreateSpecificCulture("vi-VN"),
                DateTimeStyles.None, out newBirthdate);
            if (isValidBirthdate)
            {
                customer.Birthdate = newBirthdate;
            }
            var addResult = CustomerService.Add(customer, out message);
            if (addResult != null)
            {
                return RedirectToAction("Detail", new { customerId = customer.Id });
            }
            TempData[AlertMessage.TempDataKey] = message.Replace(",", ", ");
            return View(customer);
        }

        public ActionResult Delete(long customerId)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.CustomerWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var deleteResult = CustomerService.Delete(customerId);
            if (!deleteResult)
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.ErrorOccurs;
            }
            return RedirectToAction("List");
        }

        public ActionResult Detail(long customerId)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.CustomerRead))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var customer = CustomerService.GetById(customerId);
            if (customer != null)
            {
                return View(customer);
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.NotFoundObject;
            return RedirectToAction("List");
        }

        public ActionResult Edit(long customerId)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.CustomerWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var customer = CustomerService.GetById(customerId);
            if (customer != null)
            {
                return View(customer);
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.NotFoundObject;
            return RedirectToAction("List");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(long customerId, string email, string birthdate, string address, string phone, string fullName,
            int status)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.CustomerWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            string message;
            var customer = CustomerService.GetById(customerId);
            customer.Email = email;
            DateTime newBirthdate;
            var isValidBirthdate = DateTime.TryParse(birthdate, CultureInfo.CreateSpecificCulture("vi-VN"),
                DateTimeStyles.None, out newBirthdate);
            if (isValidBirthdate)
            {
                customer.Birthdate = newBirthdate;
            }
            customer.Address = address;
            customer.Phone = phone;
            customer.FullName = fullName;
            customer.Status = status;
            var updateResult = CustomerService.Update(customer, out message);
            if (updateResult != null)
            {
                return RedirectToAction("Detail", new { customerId = customer.Id });
            }
            TempData[AlertMessage.TempDataKey] = message.Replace(",", ", ");
            return View(customer);
        }

        [ValidateInput(false)]
        public ActionResult List(long? customerId, string email, string fromBirthdate, string toBirthdate,
            string address, string phone, string fullName, int? status, int page = 1, int pageSize = 20)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.CustomerRead))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("Index", "Home");
            }
            int totalRow;
            var model = CustomerService.Search(customerId, email, fromBirthdate, toBirthdate, address, phone, fullName,
                status, page, pageSize, out totalRow);
            ViewBag.SearchId = customerId.ToString();
            ViewBag.SearchEmail = email ?? string.Empty;
            ViewBag.SearchFromBirthdate = fromBirthdate ?? string.Empty;
            ViewBag.SearchToBirthdate = toBirthdate ?? string.Empty;
            ViewBag.SearchAddress = address ?? string.Empty;
            ViewBag.SearchPhone = phone ?? string.Empty;
            ViewBag.SearchFullName = fullName ?? string.Empty;
            ViewBag.SearchStatus = status.ToString();
            ViewBag.PageList = new StaticPagedList<Customer>(model, page, pageSize, totalRow);
            ViewBag.RecordsCount = "Tổng số bản ghi: " + totalRow;
            return View(model);
        }
    }
}
